
package com.alpaak.common.utils;

import com.alpaak.common.enumtype.ErrorCodeEnum;
import com.alpaak.common.exception.BusinessException;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


/**
* @ClassName: DateExtUtil 
* @Description: 处理日期时间工具类
* @author eason
* @date 2018年2月1日 上午10:56:07
 */
public class DateExtUtil {

	//将时间字符串转化为时间戳
	public static Timestamp format(String time) {
		//匹配各种时间格式
		try {
			if(time!=null && time != ""){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				//Date parse = sdf.parse(time);
				if(isFormat(time,"yyyy-MM-dd HH:mm:ss")){
					//不用处理
				}else if(isFormat(time,"yyyyMMdd'T'HHmmss")){
					SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
					Date date = sdf2.parse(time);
					time = sdf.format(date);
				}else if(isFormat(time,"yyyy-MM-dd")){
					SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
					Date date = sdf2.parse(time);
					time = sdf.format(date);
				}else if(isFormat(time,"yyyyMMdd")){
					SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
					Date date = sdf2.parse(time);
					time = sdf.format(date);
				}else{
					throw new BusinessException(ErrorCodeEnum.TIME_FORMAT_ERROR.getErrCode(), String.format(ErrorCodeEnum.TIME_FORMAT_ERROR.getErrMsg()));
				}
				Timestamp s = Timestamp.valueOf(time);
				return s;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//判断字符串是否为指定时间格式
	@SuppressWarnings("finally")
	public static boolean isFormat(String time,String arg){
		SimpleDateFormat format = new SimpleDateFormat(arg);
		// 设置日期转化成功标识
		boolean dateflag = true;
		// 这里要捕获一下异常信息
		try {
			Date date = format.parse(time);
		} catch (ParseException e) {
			dateflag = false;
		} finally {
			// 成功：true ;失败:false
			//System.out.println("日期是否满足要求" + dateflag);
			return dateflag;
		}
	}
	
	public static Date getSpecifiedDayAfter(String specified, int d) {
		Calendar c = Calendar.getInstance();
		Date date = null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specified);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day + d);

		return c.getTime();
	}

	/*
	 * 获取一天开始时间
	 */
	public static Date getOneDayStartTime(Date date) {
		Calendar todayStart = Calendar.getInstance();
		todayStart.setTime(date);
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		//		todayStart.set(Calendar.HOUR, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		return todayStart.getTime();
	}
	
	/*
	 * 获取一天开始时间(String )
	 */
	public static String getTodayStartTime() {
		Calendar todayStart = Calendar.getInstance();
		todayStart.set(Calendar.HOUR_OF_DAY, 0);
		//		todayStart.set(Calendar.HOUR, 0);
		todayStart.set(Calendar.MINUTE, 0);
		todayStart.set(Calendar.SECOND, 0);
		todayStart.set(Calendar.MILLISECOND, 0);
		
		String today = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(todayStart.getTime());
		System.out.println(today);
		return today;
		
	}
	
	public static Date getOneDayEndTime(Date date) {

		Calendar todayEnd = Calendar.getInstance();
		todayEnd.setTime(date);
		todayEnd.set(Calendar.HOUR_OF_DAY, 23);
		//		todayEnd.set(Calendar.HOUR, 23);
		todayEnd.set(Calendar.MINUTE, 59);
		todayEnd.set(Calendar.SECOND, 59);
		todayEnd.set(Calendar.MILLISECOND, 999);
		return todayEnd.getTime();
	}
	
	public static String getTodayEndTime() {

		Calendar todayEnd = Calendar.getInstance();
		todayEnd.set(Calendar.HOUR_OF_DAY, 23);
		//		todayEnd.set(Calendar.HOUR, 23);
		todayEnd.set(Calendar.MINUTE, 59);
		todayEnd.set(Calendar.SECOND, 59);
		todayEnd.set(Calendar.MILLISECOND, 999);
		
		String today = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(todayEnd.getTime());
		System.out.println(today);
		
		return today;
	}

	//获取本周的开始时间
	public static Date getBeginDayOfWeek(Date date) {
		if (date == null) {
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
		if (dayofweek == 1) {
			dayofweek += 7;
		}
		cal.add(Calendar.DATE, 2 - dayofweek);

		return getOneDayStartTime(cal.getTime());
	}

	//获取本周的结束时间
	public static Date getEndDayOfWeek(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(getBeginDayOfWeek(date));
		cal.add(Calendar.DAY_OF_WEEK, 6);
		Date weekEndSta = cal.getTime();

		return getOneDayEndTime(weekEndSta);
	}

	/** 
	 * 获取未来 第 past 天的日期 
	 * @param past 
	 * @return 
	 */
	public static Date getFetureDate(int past) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
		Date date = calendar.getTime();

		return date;
	}
	
	public static int getDaysBetween(String dateStr) throws ParseException {
	    Date today = new Date();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	    Date compareDate = sdf.parse(dateStr);
	               
	    Calendar cal = Calendar.getInstance();
	    cal.setTime(compareDate);
	    long time1 = cal.getTimeInMillis();
	               
	    cal.setTime(today);
	    long time2 = cal.getTimeInMillis();
	    long between_days = (time2 - time1) / (1000 * 3600 * 24);
	       
	    return Integer.parseInt(String.valueOf(between_days));
	}

	/*
	 * 获取所给日期的前一天
	 */
	public static String getLastDay(String date){
		String[] s = date.split("-");
		Integer i = Integer.valueOf(s[2])-1;
		String lastdate = "";
		if(i<10){
			lastdate = s[0]+"-"+s[1]+"-0"+String.valueOf(i);
		}else{
			lastdate = s[0]+"-"+s[1]+"-"+String.valueOf(i);
		}
		return lastdate;
	}
	
	/*
	 * 截取18位身份证号获取生日日期
	 */
	public static String getBirthdayByIDCard(String id,String connector){
		if(id!=null && id.length()==18){
			String birthday = id.substring(6, 10)+connector+id.substring(10, 12)+connector+id.substring(12, 14);
			return birthday;
		}
		return null;
	}
	
	/*
	 * 处理1992-11-11 11:11:11.0 秒后多余部分
	 */
	public static String getTimeFormat(String time){
		if(time!=null && time!="" && time.length()>=19){
			time = time.substring(0, 19);
		}
		return time;
	}
	
	/*
	 * 获取当前日期昨天日期
	 */
	public static String getYesterday(){
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE,-1);
		String yesterday = new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
//		System.out.println(yesterday);
		return yesterday;
	}
	
	/*
	 * 获取当前日期
	 */
	public static String getToday(){
		Calendar cal = Calendar.getInstance();
		String today = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());
		System.out.println(today);
		return today;
	}
	
	/*
	 * 获取当前日期
	 */
	public static String getNowTime(){
		Calendar cal = Calendar.getInstance();
		String today = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(cal.getTime());
		//System.out.println(today);
		return today;
	}
	
	/*
	 * 获取当前两小时前时间
	 */
	public static String getHourAgo(int i){
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.HOUR, -i);
		String today = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(cal.getTime());
		//System.out.println(today);
		return today;
	}
	
	/*
	 * 根据日期计算年龄
	 */
	public static int getAgeByBirth(String data) {
        int age = 0;
        try {
        	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        	Date birthday = format.parse(data);
            
        	Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
           return 0;
        }
    }
	
	public static void main(String[] args) {
		int ageByBirth = getAgeByBirth("1968-06-05 00:00:00");
		System.out.println(ageByBirth);
	}
	
	
}
